﻿using FB.Data.Models;
using FB.Enums;
using FB.Membership;
using FB.Mvc.Controllers;
using FB.Providers;
using FB.Providers.EmployeeInfo;
using FCDB.Entity;
using FCDB.Entity.EntityEx;
using FCDB.Repository;
using FCDB.Web.Models;
using FCDB.Web.Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Wf5.Engine.Business;
using Wf5.Engine.Common;
using Wf5.Engine.Core;

namespace FCDB.Web.Controllers
{
    [FB.Membership.Annotations.AuthorizeOnly]
    public class FormController : FormBaseController
    {
        private WfActivityInstanceTasksRepository WfActivityInstanceTasksrepository = new WfActivityInstanceTasksRepository();
        private WfProcessRepository wfProcessRepository = new WfProcessRepository();
        private WfProcessInstanceRepository wfprocessinstanceRepository = new WfProcessInstanceRepository();
        private WfActivityInstanceRepository activityRespository = new WfActivityInstanceRepository();
        private WFWorkFlowRepository respository = new WFWorkFlowRepository();
        private WfProcessRepository wfprocessRepository = new WfProcessRepository();


        private FormRepository _formRespository = new FormRepository();

        /**
         * 
         * 判断表单是否能生成协议或者保函
         * */
        private void checkFormStats(FormCDB form)
        {
            ViewBag.CanPrintAgreement = true;
            ViewBag.CanPrintFall = true;
        }
     

        #region  担保业务流程表 已完成
        public ActionResult FormCDB()
        {
            FormRepository repository = new FormRepository();
            FormCDB form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            checkFormStats(form);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                ViewBag.HeadName = form.HeadID==null? "" : GetEmployeeByUserKey((Guid)form.HeadID).ChineseName;
                ViewBag.AName = form.RoleAID == null ? "" : GetEmployeeByUserKey((Guid)form.RoleAID).ChineseName;
                ViewBag.BName = form.RoleBID == null ? "" : GetEmployeeByUserKey((Guid)form.RoleBID).ChineseName;

                SaveCommonViewBase(form.ID, AppInstanceID);
                //checkFormStats(form);
                return View(form);
            }
            #endregion
            #region 通过表单ID
            if (!String.IsNullOrEmpty(Request["FormID"]))
            {
                long.TryParse(Request["FormID"], out FormID);
                form = repository.Get<FormCDB>(FormID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                ViewBag.HeadName = form.HeadID == null ? "" : GetEmployeeByUserKey((Guid)form.HeadID).ChineseName;
                ViewBag.AName = form.RoleAID == null ? "" : GetEmployeeByUserKey((Guid)form.RoleAID).ChineseName;
                ViewBag.BName = form.RoleBID == null ? "" : GetEmployeeByUserKey((Guid)form.RoleBID).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
               // checkFormStats(form);
                return View(form);
            }
            #endregion
            #region 新表单
            WfProcess process = wfprocessRepository.GetById(new Guid(ProcessGuid));
            if (!string.IsNullOrEmpty(Request["CopyID"]))
            {
                long.TryParse(Request["CopyID"], out AppInstanceID);
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                form.AppInstanceID = 0; form.ID = 0;
                form.ProcessGuid = new Guid(ProcessGuid);
                form.ApplyUserID = this.UserID;
                form.CreateUserID = this.UserID;
                form.DepartmentID = this.DeparmentID;
                form.CreateTime = DateTime.Now;
                form.Status = (short)FormStatusEnum.Empty;
                form.Salesman = this.UserID;
               
            }
            else
            {
                form = new FormCDB()
                {
                    CreateUserID = this.UserID,
                    Status = (short)FormStatusEnum.Empty,
                    ApplyUserID = this.UserID,
                    DepartmentID = this.DeparmentID,
                    ProcessGuid = new Guid(ProcessGuid),
                    CreateTime = DateTime.Now,
                    FormTitle = this.UserName + "--" + process.ProcessName,
                    Salesman = this.UserID,
                    Bond = 0,
                    Amount = 0,
                    HeadApr = 100,
                };
            }
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            ViewBag.Salesman = this.UserName;
            return View(form);
            #endregion

           
        }

        public ActionResult editFinance()
        {
            FormRepository repository = new FormRepository();
            FormCDB form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            checkFormStats(form);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                //checkFormStats(form);
                return View(form);
            }
            #endregion
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            ViewBag.Salesman = this.UserName;
            return View(form);
           


        }

        public ActionResult financePrint()
        {
            FormRepository repository = new FormRepository();
            FormCDB form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            checkFormStats(form);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                //checkFormStats(form);
                return View(form);
            }
            #endregion
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            ViewBag.Salesman = this.UserName;
            return View(form);
           


        }
        
        // 财务输入
        public ActionResult SaveFinance(FormCDB model)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.financiaAmount = model.financiaAmount;
            oldModel.ChargingDate = model.ChargingDate;
            oldModel.FinanceRemark = model.FinanceRemark;
            oldModel.ReceiptInfo = model.ReceiptInfo;
            oldModel.AccountRemark = model.AccountRemark;
            oldModel.Intermediary = model.Intermediary;
            oldModel.RebateTime = model.RebateTime;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            return null;
        }




        // 出纳确认收款信息
        public ActionResult SaveFormCDBFinance(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.financiaAmount = model.financiaAmount;
            oldModel.ChargingDate = model.ChargingDate  ;
            oldModel.FinanceRemark = model.FinanceRemark;
            oldModel.ReceiptInfo = model.ReceiptInfo;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }

        // 会计确认
        public ActionResult SaveFormCDBAccount(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.AccountRemark = model.AccountRemark;
            oldModel.Intermediary = model.Intermediary;
            oldModel.RebateTime = model.RebateTime;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        
        //总裁办第三部输入
        public ActionResult SaveFormCDBBeforePresident(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);

            #region 保存数据
            oldModel.SealStatus = model.SealStatus;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                FormCheckModel.CheckContent = Request["CheckContent"];
                FormCheckModel.CheckState = short.Parse(Request["CheckState"]);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        // 总裁办输入
        public ActionResult SaveFormCDBPresident(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
           
            #region 保存数据
            oldModel.IsGetFile = model.IsGetFile    ;
            oldModel.IsCharge = model.IsCharge;
            oldModel.CommissionApr = model.CommissionApr;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        // 综合室
        public ActionResult editComprehensive()
        {
            FormRepository repository = new FormRepository();
            FormCDB form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            checkFormStats(form);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                //checkFormStats(form);
                return View(form);
            }
            #endregion
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            ViewBag.Salesman = this.UserName;
            return View(form);



        }

        //  综合室输入
        public ActionResult SaveComprehensive(FormCDB model)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.Judge = model.Judge;
            oldModel.AchievementTime = model.AchievementTime;
            oldModel.CaseStatus = model.CaseStatus;
            oldModel.DataSend = model.DataSend;
            oldModel.CommissionSend = model.CommissionSend;
            oldModel.Quota = model.Quota;
            oldModel.GeneralRemark = model.GeneralRemark;
            oldModel.CommissionApr = model.CommissionApr;

            oldModel.HeadID = model.HeadID;
            oldModel.RoleAID = model.RoleAID;
            oldModel.RoleBID = model.RoleBID;
            oldModel.HeadApr = model.HeadApr;
            oldModel.RoleBApr = model.RoleBApr;
            oldModel.RoleAApr = model.RoleAApr;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            return null;
        }
        // 综合室输入
        public ActionResult SaveFormCDBComprehensive(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.Judge = model.Judge;
            oldModel.AchievementTime = model.AchievementTime;
            oldModel.CaseStatus = model.CaseStatus;
            oldModel.DataSend = model.DataSend;
            oldModel.CommissionSend = model.CommissionSend;
            oldModel.Quota = model.Quota;
            oldModel.GeneralRemark = model.GeneralRemark;
            oldModel.CommissionApr = model.CommissionApr;

            oldModel.HeadID = model.HeadID;
            oldModel.RoleAID = model.RoleAID;
            oldModel.RoleBID = model.RoleBID;
            oldModel.HeadApr = model.HeadApr;
            oldModel.RoleBApr = model.RoleBApr;
            oldModel.RoleAApr = model.RoleAApr;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }

        // 业务输入返佣
        public ActionResult SaveFormCDBBackAmount(FormCDB model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.CompanyName = model.CompanyName;
            oldModel.Bank = model.Bank;
            oldModel.AccountNo = model.AccountNo;
            oldModel.ContactName = model.ContactName;
            oldModel.ContactTpey = model.ContactTpey;
            oldModel.Due = model.Due;
            oldModel.PayCompany = model.PayCompany;
            oldModel.Remark = model.Remark;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        public ActionResult SaveFormCDB(FormCDB model)
        {
            FormRepository repository = new FormRepository();
            Guid ProcessGuid = (Guid)model.ProcessGuid;
            WfProcess process = wfProcessRepository.GetById(ProcessGuid);
            CompanyInfo companyInfo = new CompanyInfo();
            long AppInstanceID = 0;
            #region 保存表单
            if (model.ID == 0)
            {
                #region 新表单
                model.ID = IDCreateLogic.GenerateID("FormCDB", "担保业务审批表");
                AppInstanceID = IDCreateLogic.GenerateID("WfProcessInstance", "流程实例ID");
                model.FormGuid = Guid.NewGuid();
                model.CreateUserID = this.UserID;
                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.ApplyUserID = this.UserID;
                model.AppInstanceID = AppInstanceID;
                model.pact_no = companyInfo.getNo(model.Court, repository.getTodayCount(), model);
                model.FormTitle = "审批序号:" + model.AppInstanceID + " " + model.FormTitle;
                //if (model.ApplyUser != null) 
                //    model.ApplyUser = model.ApplyUser.Replace("，", ","); 
                //if (model.Respondent != null) 
                //    model.Respondent = model.Respondent.Replace("，", ","); 
                //if (model.ApplyGuarantee != null) 
                //    model.ApplyGuarantee = model.ApplyGuarantee.Replace("，", ","); 
                //if (model.ApplyIDCard != null) 
                //    model.ApplyIDCard = model.ApplyIDCard.Replace("，", ","); 
                //if (model.ApplyAddress != null) 
                //    model.ApplyAddress = model.ApplyAddress.Replace("，", ",");
                
                repository.Add(model);

                #endregion
                //保存走流程 
            }
            else
            {
                #region 更新表单
                FormCDB oldModel = repository.Get<FormCDB>(model.ID);
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.FormGuid = oldModel.FormGuid;
                model.CreateUserID = oldModel.CreateUserID;
                model.CreateTime = oldModel.CreateTime;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                AppInstanceID = (long)oldModel.AppInstanceID;
                repository.Update(model);

                #endregion
            }
            #endregion
            SaveFormsRelation(ProcessGuid, AppInstanceID, model.ID, "FormCDB");
            SaveFormAttachment(model.GetType().Name, model.ID);
            StartProcess(model.Status, ProcessGuid, process, AppInstanceID, model.FormTitle);
            return null;
        }

        // 业务修改
        public ActionResult editBusiness()
        {
            FormRepository repository = new FormRepository();
            FormCDB form = null;
            long AppInstanceID = 0;
          
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            checkFormStats(form);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCDB>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.Salesman == null) { form.Salesman = form.ApplyUserID; }
                ViewBag.Salesman = GetEmployeeByUserKey((Guid)form.Salesman).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                //checkFormStats(form);
                return View(form);
            }
            #endregion
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            ViewBag.Salesman = this.UserName;
            return View(form);



        }

        // 业务修改保存
        public ActionResult SaveBusiness(FormCDB model)
        {
            FormRepository repository = new FormRepository();
            FormCDB oldModel = repository.Get<FormCDB>(model.ID);
            #region 保存数据
            oldModel.FormTitle = model.FormTitle;
            oldModel.DepartmentID = model.DepartmentID;
            oldModel.ApplyUserID = model.ApplyUserID;
            oldModel.Salesman = model.Salesman;
            oldModel.HeadID = model.HeadID;
            oldModel.RoleAID = model.RoleAID;
            oldModel.RoleBID = model.RoleBID;

            oldModel.HeadApr = model.HeadApr;
            oldModel.RoleAApr = model.RoleAApr;
            oldModel.RoleBApr = model.RoleBApr;
            oldModel.CaseNumber = model.CaseNumber;
            oldModel.ArbitrationNumber = model.ArbitrationNumber;
            oldModel.CauseOfAction = model.CauseOfAction;
            oldModel.Court = model.Court;
            oldModel.InvoiceType = model.InvoiceType;
            oldModel.ContractAmount = model.ContractAmount;
            oldModel.Rate = model.Rate;
            oldModel.ActualCharge = model.ActualCharge;
            oldModel.ActualRate = model.ActualRate;
            oldModel.PayableAmount = model.PayableAmount;
            oldModel.PaidAmount = model.PaidAmount;
            oldModel.GuaranteeSituation = model.GuaranteeSituation;
            oldModel.Taxation = model.Taxation;
            oldModel.GuaranteeType = model.GuaranteeType;
            oldModel.ApplyIDCard = model.ApplyIDCard;
            oldModel.ApplyAddress = model.ApplyAddress;
            oldModel.ApplyGuarantee = model.ApplyGuarantee;
            oldModel.Bond = model.Bond;
            oldModel.CompanyGuarantee = model.CompanyGuarantee;
            oldModel.CompanyUser = model.CompanyUser;
            oldModel.CompanyAddress = model.CompanyAddress;
            oldModel.CompanyTel = model.CompanyTel;
            oldModel.InsuranceCooperation = model.InsuranceCooperation;
            oldModel.PropertyClues = model.PropertyClues;
            oldModel.BusinessRemark = model.BusinessRemark;
            CompanyInfo companyInfo = new CompanyInfo();
            oldModel.pact_no = companyInfo.getNo(model.Court, repository.getTodayCount(), model);

            oldModel.LBgongsi = model.LBgongsi;
            oldModel.DBjine = model.DBjine;
            oldModel.XYfeiyong = model.XYfeiyong;
            oldModel.TSDBjine = model.TSDBjine;
            oldModel.TSXYfeiyong = model.TSXYfeiyong;
            oldModel.FYfeiyong = model.FYfeiyong;
            oldModel.JLbaozhengjin = model.JLbaozhengjin;
            oldModel.BZJjine = model.BZJjine;
            oldModel.ZBjine = model.ZBjine;
            oldModel.ZBbili = model.ZBbili;
            oldModel.FCSSfeiyong = model.FCSSfeiyong;
            oldModel.FCZbili = model.FCZbili;
            oldModel.TSSHfeiyong = model.TSSHfeiyong;
            oldModel.shouju = model.shouju;
            oldModel.suifei = model.suifei;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            return null;
        }

        
        #endregion

        #region  担保返佣表 已完成
        public ActionResult FormRebate()
        {
            FormRepository repository = new FormRepository();
             FormRebate form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            //conditions.Add(new KeyValueModel() { Key = "Due", Value = "LowWord" });
            //conditions.Add(new KeyValueModel() { Key = "CompanyName", Value = "BillType" });
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
          
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormRebate>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                if (form.FormCDBID == null)
                {
                    ViewBag.FCDBName = "";
                }
                else
                {
                    ViewBag.FCDBName = repository.GetForm<FormCDB>(form.FormCDBID.Value).FormTitle;
                }
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 通过表单ID
            if (!String.IsNullOrEmpty(Request["FormID"]))
            {
                long.TryParse(Request["FormID"], out FormID);
                form = repository.Get<FormRebate>(FormID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.FormCDBID == null)
                {
                    ViewBag.FCDBName = "";
                }
                else
                {
                    ViewBag.FCDBName = repository.GetForm<FormCDB>(form.FormCDBID.Value).FormTitle;
                }
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 新表单
            WfProcess process = wfprocessRepository.GetById(new Guid(ProcessGuid));
            if (!string.IsNullOrEmpty(Request["CopyID"]))
            {
                long.TryParse(Request["CopyID"], out AppInstanceID);
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                form = repository.GetForm<FormRebate>(AppInstanceID);
                form.AppInstanceID = 0; form.ID = 0;
                form.ProcessGuid = new Guid(ProcessGuid);
                form.ApplyUserID = this.UserID;
                form.CreateUserID = this.UserID;
                form.DepartmentID = this.DeparmentID;
                form.CreateTime = DateTime.Now;
                form.FormNumber = 0;
                form.FormName ="深圳市汇盈咨询服务有限公司";
                form.Status = (short)FormStatusEnum.Empty;
            }
            else
            {
                form = new FormRebate()
                {
                    CreateUserID = this.UserID,
                    Status = (short)FormStatusEnum.Empty,
                    ApplyUserID = this.UserID,
                    DepartmentID = this.DeparmentID,
                    ProcessGuid = new Guid(ProcessGuid),
                    FormNumber = 0,
                    FormTitle = this.UserName + "--" + process.ProcessName,
                    FormDate = DateTime.Now,
                    FormName ="深圳市汇盈咨询服务有限公司"
                };
            }
            form.FormDate = DateTime.Now;
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            return View(form);
            #endregion
        }
        public ActionResult SaveFormRebate(FormRebate model)
        {
            FormRepository repository = new FormRepository();
            Guid ProcessGuid = (Guid)model.ProcessGuid;
            WfProcess process = wfProcessRepository.GetById(ProcessGuid);
            long AppInstanceID = 0;
            #region 保存表单
            if (model.ID == 0)
            {
                #region 新表单
                model.ID = IDCreateLogic.GenerateID("FormRebate", "非合同类款项支付审批表");
                AppInstanceID = IDCreateLogic.GenerateID("WfProcessInstance", "流程实例ID");
                model.FormGuid = Guid.NewGuid();
                model.CreateUserID = this.UserID;
                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.ApplyUserID = this.UserID;
                model.FormDate = DateTime.Now;
                model.AppInstanceID = AppInstanceID;
                model.FormNumber = (int)AppInstanceID;
                model.DepartmentID = this.DeparmentID;
                repository.Add(model);

                #endregion
                //保存走流程 
            }
            else
            {
                #region 更新表单
                FormRebate oldModel = repository.Get<FormRebate>(model.ID);
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.FormGuid = oldModel.FormGuid;
                model.CreateUserID = oldModel.CreateUserID;
                model.CreateTime = oldModel.CreateTime;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                AppInstanceID = (long)oldModel.AppInstanceID;
                repository.Update(model);

                #endregion
            }
            #endregion
            SaveFormsRelation(ProcessGuid, AppInstanceID, model.ID, "FormRebate");
            SaveFormAttachment(model.GetType().Name, model.ID);
            StartProcess(model.Status, ProcessGuid, process, AppInstanceID, model.FormTitle);
            return null;
        }

        public ActionResult SaveFormRebateBillDue(FormRebate model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormRebate oldModel = repository.Get<FormRebate>(model.ID);
            #region 保存数据
            oldModel.BillDue = model.BillDue;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        #endregion


        #region  担保退款表 已完成
        public ActionResult FormCost()
        {
            FormRepository repository = new FormRepository();
            FormCost form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
          //  conditions.Add(new KeyValueModel() { Key = "Due", Value = "LowWord" });
           // conditions.Add(new KeyValueModel() { Key = "CompanyName", Value = "BillType" });
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormCost>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                if (form.FormCDBID == null) { 
                     ViewBag.FCDBName = "";
                }else
                {
                    ViewBag.FCDBName = repository.GetForm<FormCDB>(form.FormCDBID.Value).FormTitle;
                }
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 通过表单ID
            if (!String.IsNullOrEmpty(Request["FormID"]))
            {
                long.TryParse(Request["FormID"], out FormID);
                form = repository.Get<FormCost>(FormID);
                ViewBag.DepartmentName = GetDepartment(form.DepartmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.ApplyUserID).ChineseName;
                if (form.FormCDBID == null)
                {
                    ViewBag.FCDBName = "";
                }
                else
                {
                    ViewBag.FCDBName = repository.GetForm<FormCDB>(form.FormCDBID.Value).FormTitle;
                }
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 新表单
            WfProcess process = wfprocessRepository.GetById(new Guid(ProcessGuid));
            if (!string.IsNullOrEmpty(Request["CopyID"]))
            {
                long.TryParse(Request["CopyID"], out AppInstanceID);
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                form = repository.GetForm<FormCost>(AppInstanceID);
                form.AppInstanceID = 0; form.ID = 0;
                form.ProcessGuid = new Guid(ProcessGuid);
                form.ApplyUserID = this.UserID;
                form.CreateUserID = this.UserID;
                form.DepartmentID = this.DeparmentID;
                form.CreateTime = DateTime.Now;
                form.FormNumber = 0;
                form.Status = (short)FormStatusEnum.Empty;
            }
            else
            {
                form = new FormCost()
                {
                    CreateUserID = this.UserID,
                    Status = (short)FormStatusEnum.Empty,
                    ApplyUserID = this.UserID,
                    DepartmentID = this.DeparmentID,
                    ProcessGuid = new Guid(ProcessGuid),
                    FormNumber = 0,
                    FormTitle = this.UserName + "--" + process.ProcessName,
                    FormDate = DateTime.Now
                };
            }
            form.FormDate = DateTime.Now;
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            return View(form);
            #endregion
        }

        public ActionResult SaveFormCost(FormCost model)
        {
            FormRepository repository = new FormRepository();
            Guid ProcessGuid = (Guid)model.ProcessGuid;
            WfProcess process = wfProcessRepository.GetById(ProcessGuid);
            long AppInstanceID = 0;
            #region 保存表单
            if (model.ID == 0)
            {
                #region 新表单
                model.ID = IDCreateLogic.GenerateID("FormCost", "非合同类款项支付审批表");
                AppInstanceID = IDCreateLogic.GenerateID("WfProcessInstance", "流程实例ID");
                model.FormGuid = Guid.NewGuid();
                model.CreateUserID = this.UserID;
                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.ApplyUserID = this.UserID;
                model.FormDate = DateTime.Now;
                model.AppInstanceID = AppInstanceID;
                model.FormNumber = (int)AppInstanceID;
                model.DepartmentID = this.DeparmentID;
                repository.Add(model);

                #endregion
                //保存走流程 
            }
            else
            {
                #region 更新表单
                FormCost oldModel = repository.Get<FormCost>(model.ID);
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.FormGuid = oldModel.FormGuid;
                model.CreateUserID = oldModel.CreateUserID;
                model.CreateTime = oldModel.CreateTime;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                AppInstanceID = (long)oldModel.AppInstanceID;
                repository.Update(model);

                #endregion
            }
            #endregion
            SaveFormsRelation(ProcessGuid, AppInstanceID, model.ID, "FormCost");
            SaveFormAttachment(model.GetType().Name, model.ID);
            StartProcess(model.Status, ProcessGuid, process, AppInstanceID, model.FormTitle);
            return null;
        }
        #endregion



        public ActionResult AddFormsFCDB()
        {
            if (Request.IsAjaxRequest())
            {
                long WorkFlowTypeID = 0;
                long.TryParse(Request["typeId"], out WorkFlowTypeID);
                string ky = Request["ky"];
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip);
                IList<WfProcessInstanceEx> processInstance = wfprocessinstanceRepository.GetFCDBlProccessInstance(this.UserID, 0, skip, take, out total, ky, WorkFlowTypeID);
                PagerModel model = new PagerModel()
                {
                    Data = processInstance,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json;
            }
            IList<WfProcessType> WorkFlowTypeList = respository.GetWorkFlowType();
            ViewBag.WorkFlowTypeList = WorkFlowTypeList;

            return View();
        }



        #region  联保保证金流程 已完成
        public ActionResult FormNoContractPay()
        {
            FormRepository repository = new FormRepository();
            FormNoContractPay form = null;
            long AppInstanceID = 0;
            long FormID = 0;
            String ProcessGuid = Request["ProcessGuid"];
            InitFormExtendInfo();
            #region 流程条件
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            List<KeyValueModel> conditions = new List<KeyValueModel>();
            conditions.Add(new KeyValueModel() { Key = "Due", Value = "LowWord" });
            conditions.Add(new KeyValueModel() { Key = "CompanyName", Value = "BillType" });
            ViewBag.Conditions = jsonConverter.Serialize(conditions);
            #endregion
            #region   通过流程找到表单
            if (!string.IsNullOrEmpty(Request["AppInstanceID"]))
            {
                long.TryParse(Request["AppInstanceID"], out AppInstanceID);
                form = repository.GetForm<FormNoContractPay>(AppInstanceID);
                ViewBag.DepartmentName = GetDepartment(form.DeparmentID).Name;

                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.DraftUserID).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 通过表单ID
            if (!String.IsNullOrEmpty(Request["FormID"]))
            {
                long.TryParse(Request["FormID"], out FormID);
                form = repository.Get<FormNoContractPay>(FormID);
                ViewBag.DepartmentName = GetDepartment(form.DeparmentID).Name;
                ViewBag.UserName = GetEmployeeByUserKey((Guid)form.DraftUserID).ChineseName;
                SaveCommonViewBase(form.ID, AppInstanceID);
                return View(form);
            }
            #endregion
            #region 新表单
            WfProcess process = wfprocessRepository.GetById(new Guid(ProcessGuid));
            if (!string.IsNullOrEmpty(Request["CopyID"]))
            {
                long.TryParse(Request["CopyID"], out AppInstanceID);
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                form = repository.GetForm<FormNoContractPay>(AppInstanceID);
                form.AppInstanceID = 0; form.ID = 0;
                form.ProcessGuid = new Guid(ProcessGuid);
                form.DraftUserID = this.UserID;
                form.CreateUserID = this.UserID;
                form.DeparmentID = this.DeparmentID;
                form.CreateTime = DateTime.Now;
                form.FormNumber = 0;
                form.Status = (short)FormStatusEnum.Empty;
            }
            else
            {
                form = new FormNoContractPay()
                {
                    CreateUserID = this.UserID,
                    Status = (short)FormStatusEnum.Empty,
                    DraftUserID = this.UserID,
                    DeparmentID = this.DeparmentID,
                    ProcessGuid = new Guid(ProcessGuid),
                    FormNumber = 0,
                    FormTitle = this.UserName + "--" + process.ProcessName,
                    FormDate = DateTime.Now
                };
            }
            form.FormDate = DateTime.Now;
            ViewBag.DepartmentName = this.DeparmentName;
            ViewBag.UserName = this.UserName;
            return View(form);
            #endregion
        }

        public ActionResult SaveFormNoContractPayBillDue(FormNoContractPay model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormNoContractPay oldModel = repository.Get<FormNoContractPay>(model.ID);
            #region 保存数据
            oldModel.BillDue = model.BillDue;

            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }

        public ActionResult SaveFormNoContractPayCompanyInfo(FormNoContractPay model, string strFormCheckModel)
        {
            FormRepository repository = new FormRepository();
            FormNoContractPay oldModel = repository.Get<FormNoContractPay>(model.ID);
            #region 保存数据
            oldModel.PayCompany = model.PayCompany;
            #endregion
            oldModel.UpdateTime = DateTime.Now;
            oldModel.UpdateUserID = this.UserID;
            repository.Update(oldModel);
            if (!string.IsNullOrEmpty(strFormCheckModel))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                FormCheckModel FormCheckModel = serializer.Deserialize<FormCheckModel>(strFormCheckModel);
                SubmitFormCheck(FormCheckModel);
            }
            return null;
        }
        public ActionResult SaveFormNoContractPay(FormNoContractPay model)
        {
            FormRepository repository = new FormRepository();
            Guid ProcessGuid = (Guid)model.ProcessGuid;
            WfProcess process = wfProcessRepository.GetById(ProcessGuid);
            long AppInstanceID = 0;
            #region 保存表单
            if (model.ID == 0)
            {
                #region 新表单
                model.ID = IDCreateLogic.GenerateID("FormNoContractPay", "非合同类款项支付审批表");
                AppInstanceID = IDCreateLogic.GenerateID("WfProcessInstance", "流程实例ID");
                model.FormGuid = Guid.NewGuid();
                model.CreateUserID = this.UserID;
                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.DraftUserID = this.UserID;
                model.FormDate = DateTime.Now;
                model.AppInstanceID = AppInstanceID;
                model.FormNumber = (int)AppInstanceID;
                repository.Add(model);

                #endregion
                //保存走流程 
            }
            else
            {
                #region 更新表单
                FormNoContractPay oldModel = repository.Get<FormNoContractPay>(model.ID);
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.FormGuid = oldModel.FormGuid;
                model.CreateUserID = oldModel.CreateUserID;
                model.CreateTime = oldModel.CreateTime;
                model.AppInstanceID = oldModel.AppInstanceID;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserID = this.UserID;
                AppInstanceID = (long)oldModel.AppInstanceID;
                repository.Update(model);

                #endregion
            }
            #endregion
            SaveFormsRelation(ProcessGuid, AppInstanceID, model.ID, "FormNoContractPay");
            SaveFormAttachment(model.GetType().Name, model.ID);
            StartProcess(model.Status, ProcessGuid, process, AppInstanceID, model.FormTitle);
            return null;
        }
        #endregion
        #region 公用
        private void InitFormExtendInfo()
        {
            ViewBag.FormAttachments = new List<FormAttachment>();
            ViewBag.FormCirculatedDocumentLogs = new List<FCDB.Entity.FormCirculatedDocumentLog>();
            ViewBag.FormsRelations = new List<FormsRelation>();
            GetProcessActivitiesCheckLog();
            ViewBag.CurrentActivityGuid = Request["ActivityGuid"];
        }
        private void UpdateProcessInstanceLastedUpdateDate(int appinstanceid)
        {

            WfProcessInstance ProcessInstance = _wfService.GetProcessInstance(appinstanceid);
            ProcessInstance.LastUpdatedDateTime = DateTime.Now;
            ProcessInstance.LastUpdatedByUserID = this.UserID;
            ProcessInstance.LastUpdatedByUserName = this.UserName;
            wfprocessinstanceRepository.Update(ProcessInstance);

        }
        /// <summary>
        /// 提交发文审核表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SubmitFormCheck(FormCheckModel model)
        {

            IList<Guid?> EmailUserIDList = new List<Guid?>();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            PerformerList pList = new PerformerList();
            WfAppRunner appRunner = new WfAppRunner()
            {
                UserID = this.UserID,
                UserName = this.UserName,
                AppInstanceID = model.AppInstanceID,
                AppName = model.AppInstanceName,
                ProcessGUID = new Guid(model.ProcessGuid)
            };
            appRunner.Conditions = new Dictionary<string, string>();
            String FormCondition = Request["FormConditionValue"];
            string CheckLogUser = Request["CheckLogUser"];
            String NextActivityGuid = Request["NextActivityGuid"];
            appRunner.Conditions.Add("CheckState", model.CheckState.ToString());
            #region 获取流程条件
            if (!String.IsNullOrEmpty(FormCondition))
            {
                List<KeyValueModel> conditions = jsonConverter.Deserialize<List<KeyValueModel>>(FormCondition);
                foreach (var item in conditions)
                {
                    appRunner.Conditions.Add(item.Key, item.Value);
                }
            }
            #endregion
            #region 获取审批用户
            if (!string.IsNullOrEmpty(CheckLogUser))
            {
                List<KeyValueModel> checkLogUserList = jsonConverter.Deserialize<List<KeyValueModel>>(CheckLogUser);
                foreach (KeyValueModel item in checkLogUserList)
                {
                    pList.Add(new Performer(new Guid(item.Key), item.Value));
                    EmailUserIDList.Add(new Guid(item.Key));
                }
            }
            #endregion
            WfExecutedResult activityResult = null;

            #region 保存审核记录
            FormCheckLog checkoklog = new FormCheckLog()
            {
                AppInstanceID = model.AppInstanceID,
                ActivityInstanceGuid = new Guid(model.ActivityGuid),
                CheckState = model.CheckState,
                CheckContent = model.CheckContent,
                CheckUserID = this.UserID,
                CheckUserName = this.UserName,
                CheckTime = DateTime.Now,
                SendUserID = model.SendUserID,
                SendUserName = model.SendUserName,
                CreateTime = model.CreateTime,
                ActivityInstanceID = model.ActivityInstanceID,
                ID = IDCreateLogic.GenerateID("FormCheckLog", "表单审核表")
            };
            _formRepository.Add(checkoklog);
            #endregion
            #region 判读是否通过
            if (model.CheckState == 2)
            {
                WfProcessInstance instance = _wfService.GetProcessInstance((int)model.AppInstanceID);
                Employee employeeItem = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                if (pList.Count(t => t.UserID == employeeItem.UserID) == 0)
                {
                    pList.Add(new Performer(employeeItem.UserID, employeeItem.ChineseName));
                }
                appRunner.NextActivityPerformers = new Dictionary<Guid, PerformerList>();
                appRunner.NextActivityPerformers.Add(new Guid(NextActivityGuid), pList);
                activityResult = _wfService.RunProcessApp(appRunner);
                UpdateProcessInstanceLastedUpdateDate((int)appRunner.AppInstanceID);
                EmailUserIDList.Add(employeeItem.UserID);
                SendEmail(EmailUserIDList, (int)appRunner.AppInstanceID);
                return null;
            }
            #endregion

            #region 判读是否会签

            ProcessModel proccessModel = new ProcessModel(appRunner.ProcessGUID);
            ActivityEntity currentActivity = proccessModel.GetActivity(new Guid(model.ActivityGuid));
            TaskManager taskManager = new TaskManager();
            if (pList.Count == 0)
            {
                ActivityEntity nextActivity = proccessModel.GetNextActivity(currentActivity.ActivityGUID);
                foreach (var roleItem in nextActivity.Roles)
                {
                    if (roleItem == "拟稿人")
                    {
                        WfProcessInstance instance = _wfService.GetProcessInstance((int)model.AppInstanceID);
                        Employee employeeItem = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                        if (pList.Count(t => t.UserID == employeeItem.UserID) == 0)
                        {
                            pList.Add(new Performer(employeeItem.UserID, employeeItem.ChineseName));
                        }
                        EmailUserIDList.Add(employeeItem.UserID);
                    }
                    else
                    {
                        AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
                        IList<string> userList = wapper.FindAllUsers(roleItem);
                        foreach (var useritem in userList)
                        {
                            Employee employeeItem = _EMPInfoUnit.EmployeeRepository.Get(t => t.UserName == useritem && t.UserID != null).First();
                            if (pList.Count(t => t.UserID == employeeItem.UserID) == 0)
                            {
                                pList.Add(new Performer(employeeItem.UserID, employeeItem.ChineseName));
                            }
                            EmailUserIDList.Add(employeeItem.UserID);
                        }
                    }
                }
            }
            appRunner.NextActivityPerformers = new Dictionary<Guid, PerformerList>();
            appRunner.NextActivityPerformers.Add(new Guid(NextActivityGuid), pList);
            IEnumerable<WfActivityInstanceTasksEx> list = taskManager.GetReadyTaskOfApp(appRunner);
            if (currentActivity.IsAllCheckState)
            {
                int count = list.Count(t => t.AssignedToUserID != this.UserID && t.ActivityState < 4 && t.State != 4 && t.TaskState < 4 && t.ActivityGUID == new Guid(model.ActivityGuid));

                if (count > 0)
                {
                    WfActivityInstanceTasksEx task = list.FirstOrDefault(t => t.TaskState < 4 && t.ActivityState < 4 && t.AssignedToUserID == this.UserID && t.ActivityGUID == new Guid(model.ActivityGuid));
                    if (task != null)
                    {
                        WfLogonUser logonUser = new WfLogonUser(this.UserID, this.UserName);
                        UpdateProcessInstanceLastedUpdateDate((int)appRunner.AppInstanceID);
                        taskManager.Complete(task.TaskID, logonUser);
                    }
                }
                else
                {
                    activityResult = _wfService.RunProcessApp(appRunner);
                    UpdateProcessInstanceLastedUpdateDate((int)appRunner.AppInstanceID);
                    SendEmail(EmailUserIDList, (int)appRunner.AppInstanceID);
                }
            }
            else
            {
                if (list.Count(t => t.TaskState >= 4 && t.ActivityState < 4 && t.State != 4 && t.ActivityGUID == new Guid(model.ActivityGuid)) > 0)
                {
                    WfActivityInstanceTasksEx task = list.FirstOrDefault(t => t.TaskState < 4 && t.AssignedToUserID == this.UserID && t.ActivityState < 4
                        && t.ActivityGUID == new Guid(model.ActivityGuid));
                    if (task != null)
                    {
                        WfLogonUser logonUser = new WfLogonUser(this.UserID, this.UserName);
                        taskManager.Complete(task.TaskID, logonUser);
                    }
                }
                else
                {
                    activityResult = _wfService.RunProcessApp(appRunner);
                    UpdateProcessInstanceLastedUpdateDate((int)appRunner.AppInstanceID);
                    SendEmail(EmailUserIDList, (int)appRunner.AppInstanceID);
                }
            }
            #endregion
            AutoSendFormCirculated(currentActivity, appRunner.AppInstanceID, appRunner.ProcessGUID);
            return null;
        }
        private void AutoSendFormCirculated(ActivityEntity activity, long AppInstanceID, Guid ProcessGUID)
        {
            if (activity.AutoRoles == null || activity.AutoRoles.Count == 0) return;
            IList<Employee> UserIds = new List<Employee>();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            List<String> CompanyList = new List<string>();
            IList<String> DeptCodeList = new List<string>();
            #region 部门归属
            if (activity.IsRoleDepartment == true)
            {
                Employee employee = null;
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                employee = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                IList<EmployeeInPosition> employeeInPosition = unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employee.EMPCode).ToList();
                foreach (var item in employeeInPosition)
                {
                    if (!string.IsNullOrEmpty(item.DEPTCode))
                    {
                        DeptCodeList.Add(item.DEPTCode);
                    }
                }
            }
            #endregion
            #region 公司归属
            if (activity.IsRoleCompany == true)
            {
                Employee employee = null;
                WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                employee = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                IList<EmployeeInPosition> employeeInPosition = unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employee.EMPCode).ToList();
                foreach (var item in employeeInPosition)
                {
                    if (!string.IsNullOrEmpty(item.COMCode))
                    {
                        CompanyList.Add(item.COMCode);
                    }
                }
            }
            #endregion
            #region 根据角色获取用户
            foreach (var roleItem in activity.AutoRoles)
            {
                if (roleItem == "拟稿人")
                {
                    WfProcessInstance instance = _wfService.GetProcessInstance((int)AppInstanceID);
                    Employee employeeItem = GetEmployeeByUserKey((Guid)instance.CreatedByUserID);
                    UserIds.Add(employeeItem);
                    continue;
                }
                IList<string> userList = wapper.FindAllUsers(roleItem);
                foreach (var useritem in userList)
                {
                    Employee employeeItem = unitinfo.EmployeeRepository.Get(t => t.UserName == useritem && t.UserID != null).First();
                    if (DeptCodeList.Count == 0 && CompanyList.Count == 0)
                    {
                        UserIds.Add(employeeItem);
                        continue;
                    }
                    if (DeptCodeList.Count > 0)
                    {
                        if (unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employeeItem.EMPCode && DeptCodeList.Contains(t.DEPTCode)).Count() > 0)
                        {
                            UserIds.Add(employeeItem);
                            continue;
                        }
                    }
                    if (CompanyList.Count > 0)
                    {
                        if (unitinfo.EmployeeInPositionRepository.Get(t => t.EMPCode == employeeItem.EMPCode && CompanyList.Contains(t.COMCode)).Count() > 0)
                        {
                            UserIds.Add(employeeItem);
                            continue;
                        }
                    }
                }
            }
            #endregion
            foreach (var item in UserIds)
            {
                FormCirculatedDocumentLog log = new FormCirculatedDocumentLog()
                {
                    AppInstanceID = AppInstanceID,
                    CheckType = 1,
                    CreateUserName = this.UserName,
                    CreateTime = DateTime.Now,
                    CreateUserID = this.UserID,
                    ProcessGUID = ProcessGUID,
                    UserID = item.UserID,
                    UserName = item.ChineseName,
                    Status = 0,
                    ID = IDCreateLogic.GenerateID("FormCirculatedDocumentLog", "流程传阅记录")
                };
                _formRespository.Add(log);
                string url = ConfigurationManager.AppSettings["FCDBHostDomain"];
                SendConsulationEmail(this.UserID, UserID, url);
            }


        }
        public ActionResult FormAttachement()
        {
            FormAttachment model = new FormAttachment();
            if (!string.IsNullOrEmpty(Request["FormType"]))
            {
                model.FormType = Request["FormType"];
            }
            if (!string.IsNullOrEmpty(Request["FormID"]))
            {
                model.FormID = long.Parse(Request["FormID"]);
            }
            return View(model);
        }

        public ActionResult GetFormAttachementFile()
        {
            string FormAttachmentFolder = ConfigurationManager.AppSettings["FormAttachmentFolder"];
            string fileName = Request["FileName"];

            var fullpath = Path.Combine(FormAttachmentFolder, fileName);
            var extension = Path.GetExtension(fullpath.ToLower());

            var contentType = System.Net.Mime.MediaTypeNames.Application.Octet;

            if (extension == ".pdf")
            {
                contentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
                Response.AddHeader("content-disposition", "inline; filename=" + fileName);

                return File(fullpath, contentType);
            }
            else if (extension == ".jpg" || extension == ".jpeg")
            {
                contentType = "image/jpeg";
            }

            return File(fullpath, contentType, fileName);
        }

        public ActionResult DeleteFormAttachement(long FormAttachmentID)
        { 
             respository.Delete<FormAttachment>(FormAttachmentID);
             return Json(FormAttachmentID, JsonRequestBehavior.AllowGet);
        }

        #region 文件上传
        [HttpPost]
        public ActionResult Upload()
        {
            string fileName = Request["name"];
            if(String.IsNullOrEmpty(fileName))
            {
                return Json(new { erron = 0 });//Demo，随便返回了个值，请勿参考
            }
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));//设置临时存放文件夹名称
            string FormAttachmentFolder = ConfigurationManager.AppSettings["FormAttachmentFolder"];   
            int index = Convert.ToInt32(Request["chunk"]);//当前分块序号
            var guid = Request["guid"];//前端传来的GUID号

            FormAttachmentFolder = Path.Combine(FormAttachmentFolder, fileRelName);//临时保存分块的目录
            if (!System.IO.Directory.Exists(FormAttachmentFolder))
                System.IO.Directory.CreateDirectory(FormAttachmentFolder);
            string filePath = Path.Combine(FormAttachmentFolder, index.ToString());//分块文件名为索引名，更严谨一些可以加上是否存在的判断，防止多线程时并发冲突
            var data = Request.Files["file"];//表单中取得分块文件
            //if (data != null)//为null可能是暂停的那一瞬间
            //{
            data.SaveAs(filePath);//报错
            //}
            return Json(new { erron = 0 });//Demo，随便返回了个值，请勿参考
        }
         [HttpPost]
        public ActionResult Merge()
        {
            var guid = Request["guid"];//GUID
            string FormAttachmentFolder = ConfigurationManager.AppSettings["FormAttachmentFolder"];            
            var fileName = Request["fileName"];//文件名
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));
            var dir = Path.Combine(FormAttachmentFolder, fileRelName);//临时文件夹          
            var files = System.IO.Directory.GetFiles(dir);//获得下面的所有文件
            string fileNameExt = fileName.Substring(fileName.LastIndexOf("."));
            string tarfileName = fileRelName + "_ " + DateTime.Now.ToString("yyyyMMddhhmmss") + fileNameExt;
            string finalPath = Path.Combine(FormAttachmentFolder, tarfileName);          
            var fs = new FileStream(finalPath, FileMode.Create);
            foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序，保证从0-N Write
            {
                var bytes = System.IO.File.ReadAllBytes(part);
                fs.Write(bytes, 0, bytes.Length);
                bytes = null;
                System.IO.File.Delete(part);//删除分块
            }
            fs.Flush();
            fs.Close();
            System.IO.Directory.Delete(dir);//删除文件夹            
            return Json(new { tarfileName = tarfileName });//随便返回个值，实际中根据需要返回
        }
        #endregion
        public ActionResult SubmitFormAttachement(FormAttachment fromAttachment)
        {          
            if (fromAttachment != null)
            {
                fromAttachment.ID = IDCreateLogic.GenerateID("FormAttachment", "表单附件ID", 1000);
                FormRepository repository = new FormRepository(); 
                if (string.IsNullOrEmpty(fromAttachment.Name))
                {
                    fromAttachment.Name = fromAttachment.Attachment;
                }
                repository.Add(fromAttachment);
                return Json(fromAttachment, JsonRequestBehavior.AllowGet);
            }
            else
            {
                fromAttachment = new FormAttachment()
                    {
                        AttachmentType = short.Parse(Request["AttachmentType"]),
                        Name = Request["Name"],
                        Remark = Request["Remark"],
                        FormType = Request["FormType"]
                    };
                if (!string.IsNullOrEmpty(Request["FormID"]))
                {
                    fromAttachment.FormID = long.Parse(Request["FormID"]);
                }
                fromAttachment.ID = IDCreateLogic.GenerateID("FormAttachment", "表单附件ID", 1000); 
                FormRepository repository = new FormRepository();

                if (string.IsNullOrEmpty(fromAttachment.Name))
                {
                    fromAttachment.Name = fromAttachment.Attachment;
                }
                
                repository.Add(fromAttachment);
                return Json(fromAttachment, JsonRequestBehavior.AllowGet);
            }
        }
        #region 私有方法



        private void StartProcess(short? Status, Guid ProcessGuid, WfProcess process, long AppInstanceID, string AppName = "")
        {
            var logger = NLog.LogManager.GetCurrentClassLogger();
            //logger.Info("Start StartProcess " + DateTime.Now.ToString("yyyy-MM-dd"));
            IList<Guid?> nUserIDList = new List<Guid?>();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            String FormCondition = Request["FormConditionValue"];
            string CheckLogUser = Request["CheckLogUser"];
            String NextActivityGuid = Request["NextActivityGuid"];
            PerformerList pList = new PerformerList();
            IDictionary<string, string> conditionKeyPairs = new Dictionary<string, string>();
            conditionKeyPairs.Add("ActivityGuid", NextActivityGuid);
            #region 获取流程条件
            if (!String.IsNullOrEmpty(FormCondition))
            {
                List<KeyValueModel> conditions = jsonConverter.Deserialize<List<KeyValueModel>>(FormCondition);
                foreach (var item in conditions)
                {
                    conditionKeyPairs.Add(item.Key, item.Value);
                }
            }
            #endregion
            #region 获取审批用户
            if (!string.IsNullOrEmpty(CheckLogUser))
            {
                List<KeyValueModel> checkLogUserList = jsonConverter.Deserialize<List<KeyValueModel>>(CheckLogUser);
                foreach (KeyValueModel item in checkLogUserList)
                {
                    pList.Add(new Performer(new Guid(item.Key), item.Value));
                    nUserIDList.Add(new Guid(item.Key));
                }
            }
            #endregion
            #region 流程
            if (Status == (short)FormStatusEnum.Working)
            {
                var initial = new WfAppRunner();
                initial.AppInstanceID = AppInstanceID;
                initial.ProcessGUID = ProcessGuid;
                initial.UserID = this.UserID;
                initial.UserName = this.UserName;
                initial.AppName = AppName;
                WfExecutedResult result = _wfService.StartProcess(initial);
                if (result.Status == WfExecutedStatus.Successed)
                {

                    initial.NextActivityPerformers = new Dictionary<Guid, PerformerList>();
                    initial.NextActivityPerformers.Add(new Guid(NextActivityGuid), pList);
                    _wfService.RunProcessApp(initial);
                    SendEmail(nUserIDList, (int)initial.AppInstanceID);
                }
            }
            //logger.Info("End StartProcess " + DateTime.Now.ToString("yyyy-MM-dd"));
            #endregion
        }

        private void SaveFormsRelation(Guid ProcessGUID, long AppInstanceID, long formID, string formTable)
        {

            FormRepository repository = new FormRepository();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            string FormsRelation = Request["FormsRelation"];
            IList<FormsRelation> FormsRelationList = jsonConverter.Deserialize<IList<FormsRelation>>(FormsRelation);
            if (FormsRelationList == null || FormsRelationList.Count() == 0) return;
            foreach (var item in FormsRelationList)
            {
                item.ID = IDCreateLogic.GenerateID("FormsRelation", "关联表单");
                item.ProcessGUID = ProcessGUID;
                item.AppInstanceID = AppInstanceID;
                item.CreateTime = DateTime.Now;
                item.CreateUserID = this.UserID;
                item.UpdateTime = DateTime.Now;
                item.UpdateUserID = this.UserID;
                item.FormID = formID;
                item.FormTable = formTable;
                repository.Add(item);
            }

        }
        private void SaveFormAttachment(string formType, long? FormID)
        {
            #region 保存附件
            FormRepository repository = new FormRepository();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            string FormAttachement = Request["FormAttachement"];
            IList<FormAttachment> formAttachmentList = jsonConverter.Deserialize<IList<FormAttachment>>(FormAttachement); 
            if (formAttachmentList == null || formAttachmentList.Count == 0) return;
            foreach (FormAttachment item in formAttachmentList)
            {
                FormAttachment attachment = repository.Get<FormAttachment>(item.ID);
                attachment.FormType = formType;
                attachment.FormID = FormID;
                repository.Update(attachment);
            }

            #endregion
        }


        #endregion

        public ActionResult UCDepartmentSelect()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();

            ViewBag.CompanyList = unitinfo.CompanyRepository.Get(t => t.RecordState == RecordState.Active  , m => m.OrderBy(t => t.Order)).ToList();
            ViewBag.DepartmentList = new List<FB.Providers.EmployeeInfo.Department>();
            return View();
        }

        public ActionResult GetDeparmentList()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            string CompanyID = Request["CompanyID"];
            List<FB.Providers.EmployeeInfo.Department> departments = new List<FB.Providers.EmployeeInfo.Department>();
            if (string.IsNullOrEmpty(CompanyID))
            {
                return Json(departments, JsonRequestBehavior.AllowGet);
            }
            departments = unitinfo.DepartmentRepository.Get(t => t.RecordState == RecordState.Active   && t.COMCode == CompanyID).ToList();
            return PartialView("UCDepartmentSelectTree", departments);
        }

        public ActionResult DialogFormsRelationSelect()
        {
            if (Request.IsAjaxRequest())
            {
                long WorkFlowTypeID = 0;
                long.TryParse(Request["typeId"], out WorkFlowTypeID);
                string ky = Request["ky"];
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip);
                IList<WfProcessInstanceEx> processInstance = wfprocessinstanceRepository.GetAllProccessInstance(this.UserID, 0, skip, take, out total, ky, WorkFlowTypeID);
                PagerModel model = new PagerModel()
                {
                    Data = processInstance,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json;
            }
            IList<WfProcessType> WorkFlowTypeList = respository.GetWorkFlowType();
            ViewBag.WorkFlowTypeList = WorkFlowTypeList;

            return View();
        }

        /// <summary>
        /// 传阅表单
        /// </summary>
        /// <returns></returns>
        public ActionResult SendFormCirculated(Guid ProcessGUID, long AppInstanceID, string UserList)
        {

            RtnMsg msg = new RtnMsg() { Status = 1 };
            JavaScriptSerializer jsonConvert = new JavaScriptSerializer();
            IList<KeyValueModel> UserIdsList = jsonConvert.Deserialize<IList<KeyValueModel>>(UserList);
            foreach (var item in UserIdsList)
            {
                if (!string.IsNullOrEmpty(item.Key))
                {
                    FormCirculatedDocumentLog log = new FormCirculatedDocumentLog()
                    {
                        AppInstanceID = AppInstanceID,
                        CheckType = 1,
                        CreateUserName = this.UserName,
                        CreateTime = DateTime.Now,
                        CreateUserID = this.UserID,
                        ProcessGUID = ProcessGUID,
                        UserID = new Guid(item.Key),
                        UserName = item.Value,
                        Status = 0,
                        ID = IDCreateLogic.GenerateID("FormCirculatedDocumentLog", "流程传阅记录")
                    };
                    _formRespository.Add(log);
                    string url = ConfigurationManager.AppSettings["FCDBHostDomain"];
                    SendConsulationEmail(this.UserID, new Guid(item.Key), url);
                }
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }


        public ActionResult SaveFormCirculatedDocumentLog()
        {

            string TaskID = Request["id"];
            FormCirculatedDocumentLog log = _formRespository.Get<FormCirculatedDocumentLog>(long.Parse(TaskID));
            if (log.CheckType == 1)
            {
                string content = string.IsNullOrEmpty(Request["content"]) ? "已閱" : Request["content"];
                log.Content = content;
                log.UpdateUserID = this.UserID;
                log.UpdateUserName = this.UserName;
                log.UpdateTime = DateTime.Now;
                log.Status = 2;
                _formRespository.Update(log);
                UpdateProcessInstanceLastedUpdateDate((int)log.AppInstanceID);
            }
            else
            {
                string content = string.IsNullOrEmpty(Request["content"]) ? "已處理" : Request["content"];
                log.Content = content;
                log.UpdateUserID = this.UserID;
                log.UpdateUserName = this.UserName;
                log.UpdateTime = DateTime.Now;
                log.Status = 2;
                _formRespository.Update(log);
                UpdateProcessInstanceLastedUpdateDate((int)log.AppInstanceID);
            }

            return null;

        }


        public ActionResult UCConsulation()
        {
            return View();
        }
        /// <summary>
        /// 征求意见
        /// </summary>
        /// <returns></returns>
        public ActionResult SendConsulation(Guid ProcessGUID, long AppInstanceID, string Question,
            string UserList, bool IsMsgNotifty, bool IsEmailNotify)
        {

            RtnMsg msg = new RtnMsg() { Status = 1 };
            JavaScriptSerializer jsonConvert = new JavaScriptSerializer();
            IList<KeyValueModel> UserIdsList = jsonConvert.Deserialize<IList<KeyValueModel>>(UserList);
            foreach (var item in UserIdsList)
            {
                if (item.Key != null)
                {
                    FormCirculatedDocumentLog log = new FormCirculatedDocumentLog()
                    {
                        AppInstanceID = AppInstanceID,
                        CheckType = 2,
                        CreateUserName = this.UserName,
                        CreateTime = DateTime.Now,
                        CreateUserID = this.UserID,
                        ProcessGUID = ProcessGUID,
                        UserID = new Guid(item.Key),
                        UserName = item.Value,
                        Status = 0,
                        Question = Question,
                        ID = IDCreateLogic.GenerateID("FormCirculatedDocumentLog", "流程傳閱記錄")
                    };
                    _formRespository.Add(log);
                    string url = ConfigurationManager.AppSettings["FCDBHostDomain"];
                    SendConsulationEmail(this.UserID, new Guid(item.Key), url);
                }
            }


            return Json(msg, JsonRequestBehavior.AllowGet);
        }
        #endregion

         

        void SendConsulationEmail(Guid fromUserID, Guid toUserID, string url)
        {
            string appName = EmailSubject.Consulation_AppName; //传阅表单
            var ToPeople = _EMPInfoUnit.EmployeeRepository.Get(t => t.UserID == toUserID && t.UserID != null).FirstOrDefault();

            var fromPeople = _EMPInfoUnit.EmployeeRepository.Get(t => t.UserID == fromUserID && t.UserID != null).FirstOrDefault();
            if (null != ToPeople)
            {
                if (string.IsNullOrEmpty(ToPeople.Email)) return;
                var mail = new FCDB.Web.EmailModel.NotificationMailModel
                {
                    From = FCDB.Web.Helpers.AppSettings.Email_Sender,
                    IsBodyHtml = true,
                };
                mail.To.Add(ToPeople.Email);
                mail.Subject = string.Format(EmailSubject.Consulation, fromPeople.ChineseName, appName);// "单据：{0} 的 {1} 查阅！"
                mail.UserName = ToPeople.ChineseName;
                mail.ProcessName = appName;
                mail.FOAHostDomain = url;
                var template = Path.Combine(ConfigurationManager.AppSettings["HtmlTemplateFolder"], "ConsulationEmailTemplate.html");
                _mailService.SendEmailNotification(template, mail);
            }
        }

        void SendEmail(IList<Guid?> userIdList, int appInstance)
        {
            if (userIdList == null || userIdList.Count == 0) return;
            WfProcessInstance Instance = _wfService.GetProcessInstance(appInstance);
            IEnumerable<WfActivityInstance> activityInstanceList = activityRespository.GetProcessRunningActivityList((long)appInstance, Instance.ProcessGUID);
            var logger = NLog.LogManager.GetCurrentClassLogger();

            string url = ConfigurationManager.AppSettings["FCDBHostDomain"];
            foreach (var item in userIdList)
            {
                var ToPeople = _EMPInfoUnit.EmployeeRepository.Get(t => t.UserID == item && t.UserID != null).FirstOrDefault();
                if (null != ToPeople)
                {
                    if (string.IsNullOrEmpty(ToPeople.Email)) return;
                    var mail = new FCDB.Web.EmailModel.NotificationMailModel
                    {
                        From = FCDB.Web.Helpers.AppSettings.Email_Sender,
                        IsBodyHtml = true,
                    };

                    mail.To.Add(ToPeople.Email);
                    mail.Subject = string.Format(EmailSubject.WorkflowProcess, Instance.CreatedByUserName, Instance.ProcessName); //"单据：{0} 的 {1} 请你审批！"
                    mail.FOAHostDomain = url;
                    mail.UserName = ToPeople.ChineseName;
                    mail.ProcessName = Instance.AppName;
                    mail.FOAHostDomain = url;
                    mail.ProcessType = Instance.ProcessName;
                    if (activityInstanceList != null && activityInstanceList.Count() > 0)
                    {
                        mail.Node = activityInstanceList.First().ActivityName;
                    }
                    else
                    {
                        mail.Node = "你的待办";
                    }
                    var template = Path.Combine(ConfigurationManager.AppSettings["HtmlTemplateFolder"], "check.html");
                    _mailService.SendEmailNotification(template, mail);
                }
            }

        }

        public ActionResult SaveProcessFormsRelation()
        {
            long AppInstanceID = long.Parse(Request["AppInstanceID"]);
            long formID = long.Parse(Request["FormID"]);
            FormRepository repository = new FormRepository();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            string FormsRelation = Request["FormsRelation"];
            IList<FormsRelation> FormsRelationList = jsonConverter.Deserialize<IList<FormsRelation>>(FormsRelation);
            if (FormsRelationList == null || FormsRelationList.Count() == 0)
            {
                RtnMsg msg = new RtnMsg()
                {
                    Status = 3,
                    Message = "缺乏要关联的表单"
                };
                JsonResult jsonResult = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = msg
                };
                return jsonResult;
            }
            else
            {
                WfProcessInstance wfprocessInstance = _wfService.GetProcessInstance((int)AppInstanceID);
                foreach (var item in FormsRelationList)
                {
                    item.ID = IDCreateLogic.GenerateID("FormsRelation", "关联表单");
                    item.ProcessGUID = wfprocessInstance.ProcessGUID;
                    item.AppInstanceID = AppInstanceID;
                    item.CreateTime = DateTime.Now;
                    item.CreateUserID = this.UserID;
                    item.UpdateTime = DateTime.Now;
                    item.UpdateUserID = this.UserID;
                    item.FormID = formID;
                    repository.Add(item);
                }
                JsonResult jsonResult = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = FormsRelationList
                };
                return jsonResult;
            }
        }

        public ActionResult DeleteFormsRelateion(String rpList)
        {
            FormRepository repository = new FormRepository();
            if (String.IsNullOrEmpty(rpList))
            {
                return Content("缺乏ID");
            }
            String[] strArr = rpList.Split(",".ToArray());
            foreach (var item in strArr)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    repository.Delete<FormsRelation>(long.Parse(item));
                }
            }
            return null;

        }


        private WfProcessInstanceRepository Repository = new WfProcessInstanceRepository();
     
    }
}
